//
//  RanPhotoPickerViewController.m
//  testAVFoundation
//
//  Created by Ran on 15/11/5.
//  Copyright (c) 2015年 gintong. All rights reserved.
//

#import "RanPhotoPickerViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "RanPhotoGroupModel.h"
#import "RanPhotoGroupCell.h"
#import "RanPhotoSelectionController.h"

#ifdef DEBUG
#   define RanPhotoPickerLog(fmt, ...)   NSLog((@"[DEBUG]%s " fmt), __PRETTY_FUNCTION__, ##__VA_ARGS__)
#else
#   define RanPhotoPickerLog(...)
#endif

static NSString *const CELL_REUSE_ID = @"24618";

@interface RanPhotoPickerViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)ALAssetsLibrary *library;
@property(nonatomic, strong)UITableView *tableview;
@property(nonatomic, strong)NSMutableArray *dataSource;

@end

@implementation RanPhotoPickerViewController

#pragma mark - LifeCycle

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [self setupParams];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}

- (void)dealloc
{
    NSLog(@"picker dealloc");
}

#pragma mark - Private

- (void)setupParams
{
    self.navigationBackText = @"返回";
    self.navigationTitle = @"选择照片";
    self.maxPhotosNum = 9;
    self.maxVideosNum = 9;
    self.maxVideosAndPhotosNum = 9;
    self.maxPhotoSize = MAXFLOAT;
    self.maxVideoSize = MAXFLOAT;
    self.sourceType = RanPhotoPickerTypePhotoOnly;
}

- (void)setupUI
{
    self.view.backgroundColor = [UIColor blackColor];
    self.title = self.navigationTitle;
    if ([self isShowedWithPresentMethod]) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:self.navigationBackText style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked)];
    }
    self.tableview = ({
        UITableView *tableview = [[UITableView alloc] initWithFrame:self.view.bounds];
        tableview.delegate = self;
        tableview.dataSource = self;
        [tableview registerNib:[UINib nibWithNibName:@"RanPhotoGroupCell" bundle:nil] forCellReuseIdentifier:CELL_REUSE_ID];
        tableview.tableFooterView = [UIView new];
        [self.view addSubview:tableview];
        tableview;
    });
}

- (BOOL)isShowedWithPresentMethod
{
    return self.navigationController.viewControllers.count <= 1;
}

- (void)loadData
{
    __weak typeof(self) weakSelf = self;
    __block NSInteger itemsCount = 0;
    ALAssetsFilter *filter = nil;
    switch (self.sourceType) {
        case RanPhotoPickerTypePhotoOnly:
            filter = [ALAssetsFilter allPhotos];
            break;
        case RanPhotoPickerTypeVideoOnly:
            filter = [ALAssetsFilter allVideos];
            break;
        case RanPhotoPickerTypePhotoAndVideo:
            filter = nil;[ALAssetsFilter allAssets];
            break;
        default:
            break;
    }
    
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    self.library = library;
    __block int a=1;
    [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
//        NSLog(@"%d", a++);
//        [group setAssetsFilter:filter];
        itemsCount = [group numberOfAssets];
        if (itemsCount) {
            RanPhotoGroupModel *model = [[RanPhotoGroupModel alloc] init];
            model.groupName = [group valueForProperty:ALAssetsGroupPropertyName];
            model.groupSize = itemsCount;
            model.groupCoverImage = [UIImage imageWithCGImage:[group posterImage]];
            model.assetsGroup = group;
            [weakSelf.dataSource addObject:model];
        }
        if (!group) {
            [weakSelf.dataSource sortUsingComparator:^NSComparisonResult(RanPhotoGroupModel *model1,RanPhotoGroupModel *model2) {
                
                return [@(model2.groupSize) compare:@(model1.groupSize)];
            }];
            [self pushWithAssetGroup:[self.dataSource[0] assetsGroup] animated:NO];
            [weakSelf.tableview reloadData];
        }
        
    } failureBlock:^(NSError *error) {
        
        RanPhotoPickerLog(@"Error! %@", error.localizedDescription);
        
    }];

}

- (void)pushWithAssetGroup: (ALAssetsGroup *)group animated: (BOOL)animated
{
    RanPhotoSelectionController *controller = [[RanPhotoSelectionController alloc] init];
    controller.assetsGroup = group;
    controller.pickerController = self;
    [self.navigationController pushViewController:controller animated:animated];
}

#pragma mark - Public

- (void)showWithPresentMethodFromViewController:(UIViewController *)viewController
{
    [viewController presentViewController:[[UINavigationController alloc] initWithRootViewController:self] animated:YES completion:nil];
}

- (void)showWithPushMethodFromViewController:(UIViewController *)viewController
{
    UINavigationController *naviController = viewController.navigationController? viewController.navigationController: (UINavigationController *)viewController;
    if ([naviController isKindOfClass:[UINavigationController class]]) {
        [naviController pushViewController:self animated:YES];
    }else{
//        RanPhotoPickerLog(@"no navigation controller is available, change to present method automatically");
        [self showWithPresentMethodFromViewController:viewController];
    }
}

#pragma mark - Event

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

}

- (void)backBtnClicked
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RanPhotoGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_REUSE_ID];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

#pragma mark - Delegate

#pragma mark UITabelViewDelegagte

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self pushWithAssetGroup:[self.dataSource[indexPath.row] assetsGroup] animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 66;
}

#pragma mark - Getter

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - Setter

@end
